#! /usr/bin/env python
"""%prog <udb filename> [options]

A simple configurator for user-password databases (UDB), which allows you to: 
 1) list the usernames in a given udb file
 2) add / modify a username in the given udb file
 3) delete an existing username from the udb file

Examples:
    udbconf <filename> -l               : list all users in `filename`
    udbconf <filename> -a <username>    : add/replace `username` in `filename`
    udbconf <filename> -d <username>    : delete `username` from `filename`

SECURITY NOTE: 
Make sure the udb file has the correct write permissions!
"""
import sys
import os
import getpass
from optparse import OptionParser 
from rpyc.utils.security import UserDB


parser = OptionParser(usage = __doc__)
parser.add_option("-l", "--list", action="store_true", dest="listonly", 
    default=False, help="List usernames and exit")
parser.add_option("-a", "--add", action="store", dest="add", metavar="USERNAME", 
    default=None, help="Set the password for the given username")
parser.add_option("-d", "--delete", action="store", dest="delete", metavar="USERNAME", 
    default=None, help="Deletes the given username")

def get_options():
    options, args = parser.parse_args()
    if len(args) != 1:
        parser.error("Missing filename!")
    if options.add and options.delete:
        parser.error("Options -a and -d are mutually exclusive!")
    
    options.filename = args[0]
    return options

def list_users(udb, options):
    if not udb:
        print "No users defined in %s" % (options.filename,)
    else:
        print "Existing users in %s:" % (options.filename,)
        for user in sorted(udb.list_users()):
            print "  %s" % (user,)

def del_user(udb, options):
    username = options.delete
    if username not in udb:
        sys.exit("User %s doesn't exist in %s" % (username, options.filename))
    
    print "Removing %s" % (username,)
    del udb[username]
    udb.save()

def set_user(udb, options):
    username = options.add
    if username not in udb:
        print "Adding %s" % (username,)
    else:
        print "Changing password for %s" % (username,)
    
    password1 = getpass.getpass("Password: ")
    password2 = getpass.getpass("Retype password: ")
    
    if password1 != password2:
        sys.exit("Passwords do not match!")
    if not password1:
        sys.exit("Password cannot be empty!")
    
    udb.set_password(username, password1)
    udb.save()

def main():
    options = get_options()
    if os.path.exists(options.filename):
        udb = UserDB.load(options.filename)
    else:        
        udb = UserDB({}, options.filename)
    
    if options.listonly:
        list_users(udb, options)
    elif options.delete:
        del_user(udb, options)
        print "OK"
    elif options.add:
        set_user(udb, options)
        print "OK"
    else:
        parser.error("No action specified")


if __name__ == "__main__":
    main()






